package ginplus

import (
	"strings"

	"github.com/gin-gonic/gin"
)

const (
	UserIdKey        = "x-user-id"
	ZoneKey          = "x-zone"
	RequestIDKey     = "x-request-id"
	DeviceIDKey      = "x-device-id"
	DeviceModelKey   = "x-device-model"
	PlatformKey      = "x-platform"
	VersionKey       = "x-version"
	AuthorizationKey = "Authorization"
	LanguageKey      = "Accept-Language"
	apiKey           = "x-api-key"
	apiSignature     = "x-api-signature"
	apiTimestamp     = "x-timestamp"
	ipKey            = "X-Forwarded-For"
	userAgent        = "User-Agent" // pc
)

type Platform string

const (
	H5Platform      = "H5"
	PCPlatform      = "PC"
	IOSPlatform     = "IOS"
	AndroidPlatform = "Android"
	WXPlatform      = "WX"
)

// GetToken 获取用户令牌
func GetToken(c *gin.Context) string {
	//var token string
	// Authorization: Bearer eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjA4NzE3ODksImlhdCI6MTU2MDg2NDU4OSwibmJmIjoxNTYwODY0NTg5LCJzdWIiOiJyb290In0.aK6TsTuEUJFKc-lIAgVUP3J1Xr47bCEiiqIGjKNF_n5oHVVeSxiVq4-hCDbE3QiGthkDme-kJsZ1xs82wnXGNg
	return c.GetHeader("Authorization")
	//prefix := "Bearer "
	//if auth != "" && strings.HasPrefix(auth, prefix) {
	//	token = auth[len(prefix):]
	//}
	//return token
}

// GetDeviceModel 获取设备型号
func GetDeviceModel(c *gin.Context) string {
	return c.GetHeader(DeviceModelKey)
}

// GetDeviceId 获取客户端设备唯一 id
func GetDeviceID(c *gin.Context) string {
	return c.GetHeader(DeviceIDKey)
}

// GetUserID 获取用户ID
func GetUserID(c *gin.Context) uint64 {
	return c.GetUint64(UserIdKey)
}

// func GetUserID(c *gin.Context) string {
// 	return c.GetHeader(UserIdKey)
// }

// GetPlatform 获取客户端平台
func GetPlatform(c *gin.Context) string {
	return c.GetHeader(PlatformKey)
}

// GetZone 获取时区
func GetZone(c *gin.Context) string {
	return c.GetHeader(ZoneKey)
}

// IsAppPlatform 判断是否是客户端登录
func IsAppPlatform(c *gin.Context) bool {
	return GetPlatform(c) == AndroidPlatform || GetPlatform(c) == IOSPlatform
}

// GetVersion 获取应用的版本号
func GetVersion(c *gin.Context) string {
	return c.GetHeader(VersionKey)
}

// SetUserID 设定用户ID
func SetUserID(c *gin.Context, userID uint64) {
	c.Set(UserIdKey, userID)
}

func RequestID(c *gin.Context) string {
	return c.GetHeader(RequestIDKey)
}

func Language(c *gin.Context) string {
	lang := strings.Split(c.GetHeader(LanguageKey), ",")[0]
	switch lang {
	case "ar", "en", "es", "id", "ja", "ko", "ms", "pt", "th", "vi", "zh-CN", "en-US":
		return lang
	default:
		return "en-US"
	}
}

func IP(c *gin.Context) string {
	ip := c.GetHeader(ipKey)
	if ip != "" && ip != "127.0.0.1" {
		return strings.Split(ip, ",")[0]
	}

	return c.ClientIP()
}

func ApiKey(c *gin.Context) string {
	return c.GetHeader(apiKey)
}

func ApiSignature(c *gin.Context) string {
	return c.GetHeader(apiSignature)
}

func ApiTimestamp(c *gin.Context) string {
	return c.GetHeader(apiTimestamp)
}

func UserAgent(c *gin.Context) string {
	return c.GetHeader(userAgent)
}
